package com.ratelimiter;



public class TokenBucketRateLimiter implements RateLimiter{
    private final Object mutex = new Object();

    //最大令牌数
    private final int maxToken;

    //产生令牌的速率，秒为单位，表示一秒产生多少个令牌。
    private int genTokenV;

    //上一次访问令牌的时间
    private long lastTime = System.currentTimeMillis() - 1000;

    //剩余的令牌
    private int excessToken;

    public TokenBucketRateLimiter( int genTokenV) {
        this.genTokenV = genTokenV;
        this.maxToken = genTokenV;
    }

    @Override
    public boolean tyrAcquire(int token) {
        synchronized (mutex) {
            long curTime = System.currentTimeMillis();
            long timeDif = curTime - this.lastTime;
            int curToken = (int) Math.min(timeDif / 1000 * this.genTokenV + this.excessToken, this.maxToken);
            if (curToken > 0) {
                curToken --;
                this.excessToken = curToken;
                lastTime = curTime;
                return true;
            }
        }

        return false;
    }
}
